package com.wc.算法基础课.E第五讲动态规划.背包问题.倍数问题;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.StringTokenizer;

/**
 * @Author congge
 * @Date 2024/3/28 8:44
 * @description https://www.acwing.com/problem/content/1236/
 */
public class Main {
    static FastReader sc = new FastReader();
    static PrintWriter out = new PrintWriter(System.out);
    static int N = 1010, M = 100010;
    static ArrayList<ArrayList<Integer>> a = new ArrayList<>();
    // f[i][j] 表示刚好i个数和的余数是j的最大值
    static int[][] f = new int[4][N];
    static int INF = 0x3f3f3f3f;
    static int n, x, k;

    public static void main(String[] args) {
        n = sc.nextInt();
        k = sc.nextInt();
        for (int i = 0; i < k; i++) a.add(new ArrayList<>());
        for (int i = 1; i <= n; i++) {
            x = sc.nextInt();
            a.get(x % k).add(x);
        }
        for (int i = 0; i <= 3; i++) {
            Arrays.fill(f[i], -INF);
        }
        f[0][0] = 0;
        for (int i = 0; i < k; i++) {
            a.get(i).sort((o1, o2) -> o2 - o1);
            for (int j = 0; j < a.get(i).size() && j < 3; j++) {
                x = a.get(i).get(j);
                for (int m = 3; m >= 1; m--) {
                    for (int t = 0; t < k; t++) {
                        f[m][t] = Math.max(f[m][t], f[m - 1][((t - x) % k + k) % k] + x);
                    }
                }
            }
        }
        out.println(f[3][0]);
        out.flush();
    }
}

class FastReader {
    StringTokenizer st;
    BufferedReader br;

    FastReader() {
        br = new BufferedReader(new InputStreamReader(System.in));
    }

    String next() {
        while (st == null || !st.hasMoreElements()) {
            try {
                st = new StringTokenizer(br.readLine());
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return st.nextToken();
    }

    int nextInt() {
        return Integer.parseInt(next());
    }

    String nextLine() {
        String s = "";
        try {
            s = br.readLine();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return s;
    }

    long nextLong() {
        return Long.parseLong(next());
    }

    double nextDouble() {
        return Double.parseDouble(next());
    }

    // 是否由下一个
    boolean hasNext() {
        while (st == null || !st.hasMoreTokens()) {
            try {
                String line = br.readLine();
                if (line == null)
                    return false;
                st = new StringTokenizer(line);
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
        return true;
    }
}
